﻿using AutoMapper;
using B.S.DataBase.MyProject.API.Appicant.Command;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyRead.API.DTOs;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.DataBase.MyProject.API.Appicant.CommandHandler
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<LoginDto>>
    {
        private readonly IBaseRepository<User> userRepo;
        private readonly IMapper mapper;
        private readonly IBaseRepository<Role> roleRepo;
        private readonly IBaseRepository<UserRole> ruRepo;

        public LoginCommandHandler(IBaseRepository<User> userRepo, IMapper mapper, IBaseRepository<Role> roleRepo, IBaseRepository<UserRole> ruRepo)
        {
            this.userRepo = userRepo;
            this.mapper = mapper;
            this.roleRepo = roleRepo;
            this.ruRepo = ruRepo;
        }


        public async Task<APIResult<LoginDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            APIResult<LoginDto> result = new APIResult<LoginDto>();
            try
            {
              
                // 查询用户信息
                var user = userRepo.Getall()
                   .FirstOrDefault(u => u.UserName == request.UserName && u.Password == request.Password);

                if (user == null)
                {
                    result.Code = APIEnum.查询失败;
                    result.Msg = "用户名与密码不匹配";
                    return await Task.FromResult(result);
                }

                // 查询用户关联的角色信息
                var roles = await ruRepo.Getall()
                   .Where(ru => ru.UserId == user.UserId)
                   .Join(roleRepo.Getall(), ru => ru.RoleId, r => r.RoleId, (ru, r) => new RoleLoginDto
                   {
                       RoleId = r.RoleId,
                       RoleName = r.RoleName,
                       UserRoleId = ru.UserRoleId
                   })
                   .ToListAsync(cancellationToken);

                // 封装登录结果 DTO
                var loginDto = new LoginDto
                {
                    UserId = user.UserId,
                    UserName = user.UserName,
                    Password = user.Password,
                    Roles = roles,
                    DepId = user.DepId,
                    NickName = user.NickName,
                    HaoId = user.HaoId,
                };
               
                result.Code = APIEnum.查询成功;
                result.Msg = "查询成功，登陆成功";
                result.data = loginDto;
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.查询失败;
                result.Msg = $"查询失败，原因：{ex.Message}";
            }

            return result;

        }
    }
}
